﻿var map = null;
var infowindow;
var setMarker = null
var markerClusterer = null;
var zoomLevel = 7;
var centerX = 53.4048084;
var centerY = 26.7249942;
var firstRun = true;

function initialize() {
    if (map == null) {
        var latlng = new google.maps.LatLng(centerX, centerY);
        var myOptions = {
            zoom: zoomLevel,
            center: latlng
        };
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);

        google.maps.event.addListener(map, 'click', function (event) {
            //placeMarker2(event.latLng);
            openDialog(event.latLng);
        });
    };

    getMarkers();

    if (firstRun == true) {
        firstRun = false;
    }
};

// Получаем все маркеры из БД
function getMarkers() {
    $.ajax({
        cache: false,
        dataType: 'json',
        type: 'GET',
        url: '/Home/GetMarkers',
        success: function (data) {
            if (data.IsSuccess == true) {
                var markers = [];
                $.each(data.Markers, function (i, item) {
                    var location = new google.maps.LatLng(parseFloat(item.Latitude), parseFloat(item.Longitude));
                    var marker = new google.maps.Marker({
                        position: location
                    });

                    marker.setValues({
                        id: item.MarkerID
                    });

                    markers.push(marker);

                    google.maps.event.addListener(marker, 'click', function () {
                        var url = '/Home/Edit?markerId=' + marker.id;
                        var dialog = $('#markerModal');
                        dialog.empty()
                            .load(url, function (response, status, xhr) {
                                if (status == 'error') {
                                    var msg = 'Sorry but there was an error: ' + xhr.status + ' ' + xhr.statusText;
                                    $.notify(msg, { globalPosition: 'bottom right' });
                                }
                                else {
                                    //alert('Load was performed.');
                                    dialog.modal({
                                        keyboard: true,
                                        show: true
                                    });
                                };
                            });
                    });
                });

                if (markerClusterer != null) {
                    markerClusterer.clearMarkers();
                }

                markerClusterer = new MarkerClusterer(map, markers, {
                    maxZoom: 13,
                    gridSize: 50,
                    styles: null
                });
            }
        },
        error: function () {
            $.notify('Ошибка при получении данных из БД', { globalPosition: 'bottom right', className: 'error' });
        }
    });
};

function placeMarker(position) {
    setMarker = new google.maps.Marker({
        position: position,
        map: map
    });

    if (typeof infowindow != 'undefined') infowindow.close();

    var content = document.createElement('div');
    content.classList.add('infoDiv');

    $.ajax({
        cache: false,
        url: '/Home/New',
        data: { lat: position.lat(), lng: position.lng() },
        type: 'GET',
        success: function (data) {
            content.innerHTML = data;

            infowindow = new google.maps.InfoWindow({
                content: content
            });

            google.maps.event.addListener(infowindow, 'closeclick', function () {
                setMarker.setMap(null);
            });

            infowindow.open(map, setMarker);
        },
        error: function (message) {
            $.notify('Something went wrong...', { globalPosition: 'bottom right', className: 'error' });
        }
    });
};

function placeMarker2(position) {
    setMarker = new google.maps.Marker({
        position: position,
        map: map
    });

    if (typeof infowindow != 'undefined') infowindow.close();

    var url = '/Home/New?' + $.param({ lat: position.lat(), lng: position.lng() });

    $('#dialog').empty().load(url, function (response, status, xhr) {
        if (status == 'error') {
            var msg = 'Sorry but there was an error: ';
            alert(msg + xhr.status + ' ' + xhr.statusText);
        }
        else {
            infowindow = new google.maps.InfoWindow({
                content: $('#dialog').html()
            });

            google.maps.event.addListener(infowindow, 'closeclick', function () {
                setMarker.setMap(null);
            });

            infowindow.open(map, setMarker);
        };
    });

    setMarker.setMap(null);
};

function openDialog(position) {
    setMarker = new google.maps.Marker({
        position: position,
        map: map,
        animation: google.maps.Animation.BOUNCE
    });

    var url = '/Home/New?' + $.param({ lat: position.lat(), lng: position.lng() });

    var dialog = $('#markerModal');

    dialog.empty()
        .on('hidden.bs.modal', function () {
            if (setMarker != null) {
                setMarker.setMap(null);
                setMarker = null;
            }
        })
        .load(url, function (response, status, xhr) {
            if (status == 'error') {
                var msg = 'Sorry but there was an error: ' + xhr.status + ' ' + xhr.statusText;
                $.notify(msg, { globalPosition: 'bottom right' });
            }
            else {
                //alert('Load was performed.');
                dialog.modal({
                    keyboard: true,
                    show: true
                });
            };
        });
};

function insertMarker() {
    var form = $('#insertForm');
    var formData = form.serialize();
    var url = form.attr('action');

    $.post(url, formData, function (data) {
        if (data.IsSuccess == true) {
            $.notify(data.Message, { globalPosition: 'bottom right', className: 'success' });
            $('#markerModal').modal('hide');
            // Убираем маркер
            if (setMarker != null) {
                setMarker.setMap(null);
            }
            centerX = map.getCenter().lat();
            centerY = map.getCenter().lng();
            // и перезагружаем данные
            initialize();
        }
        else {
            $.notify(data.Message, { globalPosition: 'bottom right', className: 'error' });
            var captchaObj = $('#CaptchaCode').get(0).Captcha;
            if (captchaObj != null) {
                captchaObj.ReloadImage();
            };
        };
    });
};

function updateMarker() {
    var form = $('#editForm');
    var formData = form.serialize();
    var url = form.attr('action');
    $.post(url, formData, function (data, status, xhr) {
        console.log(status);
        if (data.IsSuccess == true) {
            $.notify(data.Message, { globalPosition: 'bottom right', className: 'success' });
            $('#markerModal').modal('hide');
        }
        else {
            $.notify(data.Message, { globalPosition: 'bottom right', className: 'error' });
        };
    });
};

function showLogonDialog() {
    var dialog = $('#loginModal');
    dialog.empty().load('/Home/OpenLogin', function (response, status, xhr) {
        if (status == 'error') {
            var msg = 'Sorry but there was an error: ' + xhr.status + ' ' + xhr.statusText;
            $.notify(msg, { globalPosition: 'bottom right' });
        }
        else {
            dialog.modal({
                keyboard: true,
                show: true
            })
        }
    });
};

function checkLogin() {
    var form = $('#loginForm');
    var formData = form.serialize();
    var url = form.attr('action');
    console.log(formData);
    $.post(url, formData, function (data, status, xhr) {
        if (data.IsSuccess) {
            $('#loginModal').modal('hide');
            $.notify('Вы прошли проверку', { globalPosition: 'bottom right', className: 'success' });
            $('#loginButton').load('/Home/GetLoginButton');
        }
        else {
            $.notify('Неправильное имя пользователя или пароль', { globalPosition: 'bottom right' });
        }
    });
};

function signOut() {
    $('#loginButton').load('/Home/LogOff');
}

function submitSearch() {
    var form = $('#searchForm');
    var url = form.attr('action');
    var formData = form.serialize();
    $.post(url, formData, function (data) {
        $('#searchResult').empty().removeClass('hidden').html(data);
    });
};

function getPage(page) {
    var form = $('#searchForm');
    var url = form.attr('action');
    var formData = form.serialize();
    formData += '&Page=' + page;
    $.post(url, formData, function (data) {
        $('#searchResult').empty().removeClass('hidden').html(data);
    });
}

function clearSearch() {
    $('#searchResult').addClass('hidden').empty();
};

function showOnMap(lat, lng) {
    map.setZoom(14);
    map.panTo(new google.maps.LatLng(lat, lng));
};

google.maps.event.addDomListener(window, 'load', initialize);